package cn.saltybe.analysis.controller.api.newHouse;

import cn.saltybe.analysis.service.NewHouseServiceImpl;
import cn.saltybe.analysis.entity.data.NewHouse;
import cn.saltybe.analysis.util.ApiResponse;
import com.geccocrawler.gecco.annotation.Request;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping(value = "/api/new-house")
public class NewHouseAPI {
    private NewHouseServiceImpl newHouseService;

    @Autowired
    public void setNewHouseService(NewHouseServiceImpl newHouseService) {
        this.newHouseService = newHouseService;
    }

    @ResponseBody
    @GetMapping("list")
    public String list(
            @RequestParam(value = "page", required = false, defaultValue = "0") int page,
            @RequestParam(value = "search", required = false, defaultValue = "") String search,
            HttpServletRequest request) throws Exception {
        if (page <= 0) page = 0;
        final int limit = 10;
        List<NewHouse> list = this.newHouseService.query(search, page * limit, limit);

        JsonObject result = new JsonObject();
        result.addProperty("count", this.newHouseService.count(search));
        result.add("list", new Gson().toJsonTree(list).getAsJsonArray());
        return ApiResponse.buildSuccessResponse(result).toString();
    }

    @ResponseBody
    @GetMapping("")
    public String get(
            @RequestParam(value = "id") int id
    ) throws Exception {
        JsonObject result = new Gson().toJsonTree(this.newHouseService.get(id)).getAsJsonObject();
        return ApiResponse.buildSuccessResponse(result).toString();
    }
}
